
package com.common.widget.audio;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;

import android.app.Activity;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.common.android.utils.ToastUtils;
import com.common.android.utils.audio.AudioRecordManager;
import com.common.android.utils.audio.AudioRecordManager.ERROR;
import com.common.android.utils.audio.AudioRecordManager.onAudioRecordListener;
import com.common.android.utils.audio.AudioRecordOperationManager.IRecordOperation;
import com.common.utils.StarAppUtils;
import com.product.android.utils.FileHelper;
import com.starappallcommon.R;
/**
 * 聊天录音
 * 
 * <br>Created 2014-6-9 下午5:39:13
 * @version  
 * @author   cb		
 *
 * @see
 */
public class StarappTalkPopWindow implements IRecordOperation{
    public static final int MAX_RECORD_TIME=120;
    private static final String TOTAL="/120\"";
    private View mMenuView;
    private PopupWindow mPopupWindow;
    private Activity mContext;
    private StarappVolumeView volumeView;
    private TextView mCancelTextView;
    private ImageView mImageView;
    private Handler mParentHandler;
    private int modle = 0;
    private TextView tvTimer;
    private View mAnchorView;
    private int mStatuBarHeight;
    private TextView tvRemain;
    private AudioRecordManager mAudioRecordManager;
    private long mRecoredTime;
	private boolean mIsInitError=false;
	private final int defaultHeight = 38;
	private final int remainMin = 10;
	/**
	 * 
	 * Creates a new instance of StarappTalkPopWindow.
	 * <br>Created 2014-6-9 下午5:40:41
	 * @param context 上下文
	 * @param anchor view
	 */
    public StarappTalkPopWindow(Activity context,View anchor) {
        mContext = context;
        mAnchorView=anchor;
        initView();
        mAudioRecordManager=new AudioRecordManager(recordListener);
        createNewAudioFile();
        mAudioRecordManager.setMaxRecordTime(MAX_RECORD_TIME);
    }
    
    /**
     * 生成一个新的录音文件
     * <br>Created 2014-5-22 下午2:59:44
     * @author       cb
    */
    private void createNewAudioFile(){
    	mIsInitError=false;
    	String path="";
    	 try {
 			path = FileHelper.getBasePath("audio") + File.separator + "androidVoice"
 			        + System.currentTimeMillis() + ".amr";
 		} catch (IOException e) {
 			e.printStackTrace();
 			try {
 				path=mContext.getExternalFilesDir("audio").getAbsolutePath()+File.separator + "androidVoice"
 				        + System.currentTimeMillis() + ".amr";
			} catch (Exception e2) {
				//在某些特殊的情况下，这边会出现空指针异常……
				e2.printStackTrace();
			}
 			
 		}
    	if (TextUtils.isEmpty(path)){
    		mIsInitError=true;
    	}
    	mAudioRecordManager.setRecrodPath(path);
    }

    /**
     * 初始化View
     * 
     * <br>Created 2014-6-9 下午5:41:38
     * @author        :  cb
     */
    private void initView() {
        LayoutInflater inflater = mContext.getLayoutInflater();
        mMenuView = inflater.inflate(R.layout.starapp_audio_record, null);
        volumeView = (StarappVolumeView)mMenuView.findViewById(R.id.volumeView);
        mCancelTextView=(TextView)mMenuView.findViewById(R.id.audio_item_cancel_tv);
        mImageView=(ImageView)mMenuView.findViewById(R.id.audio_item_rcd);
        tvTimer=(TextView)mMenuView.findViewById(R.id.tvTimer);
        tvTimer.setTextColor(0xffffffff);
        tvRemain=(TextView)mMenuView.findViewById(R.id.tvRemain);
        setRecordedTime(0);
        getStatuBarHeight();
        DisplayMetrics dm=mContext.getResources().getDisplayMetrics();
        int totalHeight=dm.heightPixels-mStatuBarHeight-mAnchorView.getHeight();
        mPopupWindow = new PopupWindow(mMenuView, dm.widthPixels,totalHeight);
        mPopupWindow.setFocusable(true);
        ColorDrawable dw = new ColorDrawable(0x00);
        mPopupWindow.setBackgroundDrawable(dw);
        mPopupWindow.setAnimationStyle(android.R.style.Animation_Toast);
        
    }

    /**
     * @n<b>函数名称</b>     :getStatuBarHeight
     * @brief 获取
     * @see
     * @version    Ver 1.3.x
     * @param  
     * @<b>作者</b>          :  cb
     * @<b>创建时间</b>      :  2014-1-23下午6:18:32      
    */
    private void getStatuBarHeight(){
         try { 
             Class<?> c = Class.forName("com.android.internal.R$dimen"); 
             Object obj = c.newInstance(); 
             Field field = c.getField("status_bar_height"); 
             int x = Integer.parseInt(field.get(obj).toString()); 
             mStatuBarHeight = mContext.getResources().getDimensionPixelSize(x); 
         } catch (Exception e1) { 
             e1.printStackTrace();
             mStatuBarHeight= defaultHeight;
         } 
    }
    
    /**
     * @n<b>函数名称</b>     :showMenuWindow
     * @brief 显示录音窗口
     * @see
     * @version    Ver 1.3.x
     * @param  
     * @<b>作者</b>          :  cb
     * @<b>创建时间</b>      :  2014-1-23下午6:18:22      
    */
    @Override
    public void showMenuWindow() {
        if (mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
        } else {
        	initImg();
        	int top=mStatuBarHeight;
            mPopupWindow.showAtLocation(mAnchorView,Gravity.TOP, 0, top);
            mPopupWindow.setFocusable(true);
        }
    }

    /**
     * @n<b>函数名称</b>     :switchImg
     * @brief 切换录音/取消状态显示
     * @see
     * @version    Ver 1.3.x
     * @param  
     * @<b>作者</b>          :  cb
     * @<b>创建时间</b>      :  2014-1-23下午6:16:55      
    */
    @Override
    public void switchImg() {
        if (modle == AudioRecordManager.STATE_RECORD) {
        	mCancelTextView.setText(mContext.getResources().getString(R.string.chat_cancel_audio_second_step));
        	tvTimer.setVisibility(View.GONE);
        	mCancelTextView.setBackgroundResource(R.drawable.chat_audio_item_canel_tv_bg);
        	mImageView.setBackgroundResource(R.drawable.chat_icon_mac);
        	volumeView.setVisibility(View.GONE);
            modle = AudioRecordManager.STATE_CANCEL;
        } else {
        	initImg();
        }
    }
    
    /**
     * @n<b>函数名称</b>     :initImg
     * @brief 初始化背景图片(默认是在录音状态)
     * @see
     * @version    Ver 1.3.x
     * @param  
     * @<b>作者</b>          :  cb
     * @<b>创建时间</b>      :  2014-1-23下午6:17:12      
    */
    private void initImg(){
    	tvTimer.setVisibility(View.VISIBLE);
    	mCancelTextView.setText(mContext.getResources().getString(R.string.chat_cancel_audio_first_step));
    	mCancelTextView.setBackgroundResource(R.drawable.chat_audio_hint_tv_bg);
    	volumeView.setVisibility(View.VISIBLE);
        modle = AudioRecordManager.STATE_RECORD;
    }
    
    

    /**
     * @n<b>函数名称</b>     :getModle
     * @brief 获取当前状态(录音/取消)
     * @see
     * @version    Ver 1.3.x
     * @param  @return
     * @return int
     * @<b>作者</b>          :  cb
     * @<b>创建时间</b>      :  2014-1-23下午6:17:43      
    */
    @Override
    public int getModle() {
        return modle;
    }

    /**
     * @n<b>函数名称</b>     :hideMenuWindow
     * @brief 隐藏录音窗口
     * @see
     * @version    Ver 1.3.x
     * @param  
     * @<b>作者</b>          :  cb
     * @<b>创建时间</b>      :  2014-1-23下午6:17:57      
    */
    @Override
    public void hideMenuWindow() {
        if (mPopupWindow!=null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
        }
    }

    /**
     * @n<b>函数名称</b>     :audioStart
     * @brief 开始录音
     * @see
     * @version    Ver 1.3.x
     * @param  @return
     * @return boolean
     * @<b>作者</b>          :  cb
     * @<b>创建时间</b>      :  2014-1-23下午6:12:11      
    */
    @Override
	public boolean audioStart() {
    	if (mIsInitError){
    		//初始化异常
    		ToastUtils.display(R.string.chat_error_audio_init);
    		return false;
    	}
    	createNewAudioFile();
        return mAudioRecordManager.audioStart();
    }

    /**
     * @n<b>函数名称</b>     :audioFinish
     * @brief 录音结束
     * @see
     * @version    Ver 1.3.x
     * @param  
     * @<b>作者</b>          :  cb
     * @<b>创建时间</b>      :  2014-1-23下午6:14:44      
    */
	@Override
    public void audioFinish() {
    	mAudioRecordManager.audioFinish();
//    	if (mRecordState==STATE_RECORDING){
//    		//如果正在录音,先停止,获取录音成功与否的状态
//    		mRecordState=audioStop();
//    	}
//    	hideMenuWindow();
//        if (mRecordState==STATE_SUCCESS && parentHandler != null) {
//        	//录音成功
//            Message msg = parentHandler.obtainMessage();
//            msg.what = 0;
//            Bundle bundle = new Bundle();
//            bundle.putString("fileName", mPath);
//            msg.setData(bundle);
//            parentHandler.sendMessage(msg);
//        } else {
//        	//录音失败
//	        handler.sendEmptyMessage(STATE_FAIL);
//        }
    }

	/**
	 * 显示已录音的时间
	 * 
	 * <br>Created 2014-6-6 下午5:26:23
	 * @param time 播放时间
	 * @return int
	 * @author        :  cb
	 */
    private int setRecordedTime(long time){
    	if (time>MAX_RECORD_TIME){
    		time=MAX_RECORD_TIME;
    	}
    	mRecoredTime=time;
		String timeStr=time+TOTAL;
    	tvTimer.setText(timeStr);
    	//获取剩余的录音时间
    	int remain=(int) (MAX_RECORD_TIME-time);
        if (remain<=remainMin){
        	tvRemain.setVisibility(View.VISIBLE);
        	String text=mContext.getString(R.string.chat_audio_remain,remain);
        	tvRemain.setText(text);
        }
		return 0;
    }
    
    private onAudioRecordListener recordListener=new onAudioRecordListener() {
		@Override
		public void onVolumeChanged(int volume,long time) {
			setvolume(volume);
			setRecordedTime(time);
		}
		
		@Override
		public void onRecordSuccess(String path, long time) {
			if (mParentHandler!=null){
				Message msg = mParentHandler.obtainMessage();
	            msg.what = 0;
	            Bundle bundle = new Bundle();
	            bundle.putString("fileName", path);
	            if (mRecoredTime<=0){
	            	bundle.putInt("duration", StarAppUtils.millsec2Sec(time));	
	            }else{
	            	bundle.putInt("duration", (int) mRecoredTime);	
	            }
	            msg.setData(bundle);
	            mParentHandler.sendMessage(msg);
			}
		}
		
		@Override
		public void onRecordStart() {
        	tvRemain.setVisibility(View.GONE);
		}
		
		@Override
		public void onRecordFail(int failType, String errMsg) {
			if (mPopupWindow != null && mPopupWindow.isShowing()) {
                mPopupWindow.dismiss();
            }
			switch (failType) {
			case ERROR.TIME_TOO_SHORT:
				ToastUtils.display(R.string.recording_too_short);
				break;
			case ERROR.STOP_EXCEPTION:
				ToastUtils.display(R.string.recording_error_stop);
				break;
			case ERROR.START_EXCEPTION:
				ToastUtils.display(R.string.recording_error_start);
				break;
			case ERROR.STILL_RECORDING:
				ToastUtils.display(R.string.recording_error_recording);
				break;
			case ERROR.EMPTY_FILE_NAME:
				ToastUtils.display(R.string.recording_error_empty_file);
				break;
			default:
				ToastUtils.display(mContext, R.string.error_on_recording);
				break;
			}
		}
		
	    /**
	     * @n<b>函数名称</b>     :setvolume
	     * @brief 设置音量
	     * @see
	     * @version    Ver 1.3.x
	     * @param  @param value
	     * @return void
	     * @<b>作者</b>          :  cb
	     * @<b>创建时间</b>      :  2014-1-23下午6:18:11      
	    */
	    public void setvolume(int value) {
	        volumeView.setVolume(value);
	    }
	};
	@Override
	public void setAudioHandler(Handler handler) {
		mParentHandler=handler;
	}
}
